<?php

// Created by Khanh Nam
class InvoicesController extends Controller {
    public $layout = '//layouts/customer';
    public function filters() {
        return array(
            'accessControl', // perform access control for CRUD operations
            array(
                'application.filters.RequireLoginFilter',
            ),
        );
    }

    /**
     * Specifies the access control rules.
     * This method is used by the 'accessControl' filter.
     * @return array access control rules
     */
    public function accessRules() {
        return array(
            array('allow', // allow all users to perform 'index' and 'view' actions

                'users' => array('@'),
            ),
            array('deny', // deny all users
                'users' => array('*'),
            ),
        );
    }

    public function actionIndex($id) {
        $location = Locations::model()->findByPk($id);
         if($location->custno!=Yii::app()->user->custno)   
             throw new CHttpException(404, 'The requested page does not exist.');
        $this->render('index', array(
            'location' => $location
        ));
    }
    public function actionCancel($invoice){
        $model=$this->loadModel($invoice);
        if($model->status!=0){
            $model->delete();
        }else{
            InvoiceEmp::model()->deleteAll('invoice=:invoice AND status!=0', array('invoice' => $invoice));
            InvoiceLedger::model()->deleteAll('invoice=:invoice AND status!=0', array('invoice' => $invoice));
        }
        $this->redirect(array('index','id'=>$model->location->id));
    }
    public function actionUpdate($invoice) {
        
        $model = $this->loadModel($invoice);
        
        if (isset($_POST['Invoice'])) {

            $model->attributes = $_POST['Invoice'];
            $model->status=0;
            if ($model->save()) {                                               
                Yii::app()->end();
            }else{
                echo CActiveForm::validate($model);
            }
        }
        outputJsByList(Warehouse::model()->getList(), 'warehouse');
        outputJsByList(Employees::model()->getEmployeeList(), 'employee');
        outputJsByList(Equipment::model()->getListByLocation($model->custno, $model->locno), 'equipment');
        $location = Locations::model()->find('locno=:locno', array('locno' => $model->locno));
        $customer = Customers::model()->find('custno=:custno', array('custno' => $location->custno));
        $this->render('update', array('location' => $location,
            'customer' => $customer,
            'model' => $model));
    }

    public function actionCreate($id) {
        outputJsByList(Warehouse::model()->getList(), 'warehouse');
        outputJsByList(Employees::model()->getEmployeeList(), 'employee');
        $model = new Invoice();
        $model->invoice = date('Y') . '-' . Counters::model()->getNextNumber('invoice');
        $model->invoicedate = date('Y-m-d');
        $location = Locations::model()->findByPk($id);
        $customer = Customers::model()->find('custno=:custno', array(
            'custno' => $location->custno));
        $model->custno = $location->custno;
        $model->locno = $location->locno;
        $model->shipaddress1 = $location->add1;
        $model->shipaddress2 = $location->add2;
        $model->shipCSZ = "$location->city $location->state $location->zip";
        $model->shipname = $location->locname;
        $model->period = date('Ym');
        $model->taxcode = $location->taxcode;
        
        //some default setting from parent company
        $customer=$model->customer;
        $model->salesperson=$customer->salesperson;
        $model->pricecode=$customer->pricecode;
        $model->slterms=$customer->terms;
        $model->invoicedate=date('Y-m-d');
        $model->status=1;       
        $model->save();
        /*
        if (isset($_POST['Invoice'])) {

            $model->attributes = $_POST['Invoice'];
            
            if ($model->save()) {
                
                $this->redirect(array('update', 'invoice' => $model->invoice));
            }
        }
         * 
         */
        $this->redirect(array('update', 'invoice' => $model->invoice));
    }

    public function actionDelete($id) {
        
        $this->loadModel($id)->delete();
        
    }

    public function actionGetBillToData($id, $custno) {
        $data = array();
        if ($id != 0)
            $model = Locations::model()->findByPk($id);
        else {
            $model = Customers::model()->findByPk($custno);
        };

        $data['add1'] = $model->add1;
        $data['add2'] = $model->add2;
        $data['csz'] = "$model->city $model->state $model->zip";
        echo json_encode($data);
    }

    /**
     * Returns the json endcoded item params(price, etc)
     * @param string item description
     */
    public function actionGetItemData($description) {

        //echo $description;

        $criteria = new CDbCriteria;
        $criteria->compare('description', $description);
        $model = Inventory::model()->find($criteria);


        $data = array();
        $data['price'] = $model->baseprice;
        $data['partno'] = $model->partno;

        echo json_encode($data);
    }

    public function actionGetInvoiceLists($locno, $page=1, $sort=NULL, $dir=NULL) {
        //we decrease $page by 1 because in Extjs first page is 1, but in our sql first page is 0;
        if ($page > 0)
            $page--;

        $employers = new CActiveDataProvider('Invoice', array(
                    'criteria' => array(
                        'condition' => "locno='$locno'",
                        'order' => $sort != NULL ? $sort . ' ' . $dir : '',
                    ),
                    'pagination' => array(
                        'pageSize' => 20,
                        'currentPage' => $page,
                    ),
                ));

        $empList = array();
        if ($employers->getTotalItemCount() > 0) {
            $empList['totalCount'] = $employers->getTotalItemCount();
            $empList['type'] = 'Items';
            foreach ($employers->getData() as $i=>$item) {
                $empList['data'][] = $item->getAttributes();
            
            }
            echo json_encode($empList);
        }
        Yii::app()->end();
    }

    /**
     * Returns the data model based on the primary key given in the GET variable.
     * If the data model is not found, an HTTP exception will be raised.
     * @param integer the ID of the model to be loaded
     */
    public function loadModel($id) {
        $model = Invoice::model()->findByPk($id);
        if ($model === null)
            throw new CHttpException(404, 'The requested page does not exist.');
        return $model;
    }

}

?>
